<template>
  <div
    ref="tableContainer"
    style="width: calc(100vw - 200px); height: 100vh"
  ></div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as VTable from "@visactor/vtable";
import data from "../json/tree-perspective.json"

defineOptions({
  name: "MyVTableTreePerspective",
});

const tableContainer = ref(null);

const option = ref({
  records: data,
  rows: [
    {
      dimensionKey: "Category",
      title: "Category",
      headerStyle: {
        textStick: true,
      },
      width: "auto",
    },
    {
      dimensionKey: "Sub-Category",
      title: "Sub-Catogery",
      headerStyle: {
        textStick: true,
      },
      width: "auto",
    },
  ],
  columns: [
    {
      dimensionKey: "Region",
      title: "Region",
      headerStyle: {
        textStick: true,
      },
      width: "auto",
    },
    {
      dimensionKey: "Segment",
      title: "Segment",
      headerStyle: {
        textStick: true,
      },
      width: "auto",
    },
  ],
  indicators: [
    {
      indicatorKey: "Quantity",
      title: "Quantity",
      width: "auto",
      showSort: false,
      headerStyle: {
        fontWeight: "normal",
      },
      style: {
        padding: [16, 28, 16, 28],
        color(args) {
          if (args.dataValue >= 0) return "black";
          return "red";
        },
      },
    },
    {
      indicatorKey: "Sales",
      title: "Sales",
      width: "auto",
      showSort: false,
      headerStyle: {
        fontWeight: "normal",
      },
      format: (rec) => {
        return "$" + Number(rec).toFixed(2);
      },
      style: {
        padding: [16, 28, 16, 28],
        color(args) {
          if (args.dataValue >= 0) return "black";
          return "red";
        },
      },
    },
    {
      indicatorKey: "Profit",
      title: "Profit",
      width: "auto",
      showSort: false,
      headerStyle: {
        fontWeight: "normal",
      },
      format: (rec) => {
        return "$" + Number(rec).toFixed(2);
      },
      style: {
        padding: [16, 28, 16, 28],
        color(args) {
          if (args.dataValue >= 0) return "black";
          return "red";
        },
      },
    },
  ],
  corner: {
    titleOnDimension: "row",
    headerStyle: {
      textStick: true,
    },
  },
  dataConfig: {
    sortRules: [
      {
        sortField: "Category",
        sortBy: ["Office Supplies", "Technology", "Furniture"],
      },
    ],
    totals: {
      row: {
        showSubTotals: true,
        subTotalsDimensions: ["Category"],
        subTotalLabel: "subtotal",
      },
    },
  },
  rowHierarchyType: "tree",
  widthMode: "standard",
});

onMounted(() => {
  option.value.container = tableContainer.value;
  const tableInstance = new VTable.PivotTable(option.value);
});
</script>

